#!/usr/bin/python3
import re
import random
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter.font import Font
import sys, os
import sqlite3
import urllib.parse
import urllib.request
from lxml import etree
from myutils.maintain import *
import chardet

def get_mean( word ):
    db1 = sqlite3.connect( os.path.join(os.getcwd(), 'mydict.db') )
    cu1 = db1.cursor()
    sql1 = "select mean from dict where word=?"
    cu1.execute(sql1, (word, ))
    mean=cu1.fetchone()
    cu1.close()
    if mean!=None:
        return mean[0]
    else:
        return '查不到，请点击“百度查询”，结果将自动加入本地字典。\n'

def detect_encoding(fn):
    with open(fn, 'rb') as f:
        data = f.read()
        f_charInfo=chardet.detect(data)
    
    return f_charInfo['encoding']

def file_input_words(filep1):
    enc = detect_encoding(filep1)
    #print(enc)
    file1=open(filep1,encoding=enc)
    sp1=[]
    try:
        for s1 in file1:
            if len(s1)>0:
                sp2=re.split('[ \t\n\r]+',s1)
                for s2 in sp2:
                    if len(s2)>0:
                        sp1+=[s2,]
    finally:
        file1.close()
    return sp1

def exist_in_set(set1,s1):
    for e1 in set1:
        if e1==s1:
            return True
    return False

def get_unique_bytes(words):
    b1_set=set()
    for w1 in words:
        for i in range(len(w1)):
            if exist_in_set(b1_set,w1[i:i+1])==False:
                b1_set.add(w1[i:i+1])
    return b1_set

def rand_bytes(bytes_set):
    s1=list(bytes_set)
    while len(s1)>0:
        i=random.randint( 0, len(s1)-1 )
        yield s1.pop(i)

def get_rwords(byte1,words):
    for w1 in words:
        if re.search(byte1,w1) is not None:
            yield w1

class Window:
    def __init__(self, title='识字抽查', width=800, height=600, staFunc=bool, stoFunc=bool):
        self.w = width
        self.h = height
        self.stat = True
        self.staFunc = staFunc
        self.stoFunc = stoFunc
        self.staIco = None
        self.stoIco = None
        self.root = tk.Tk(className=title)
        self.curFilename=''

    def center(self):
        ws = self.root.winfo_screenwidth()
        hs = self.root.winfo_screenheight()
        x = int( (ws/2) - (self.w/2) )
        y = int( (hs/2) - (self.h/2) )
        self.root.geometry('{}x{}+{}+{}'.format(self.w, self.h, x, y))

    def packBtn(self):
        self.f1=tk.Frame(self.root)
        self.f2=tk.Frame(self.root)
        self.f1.pack(side='top')
        self.f2.pack(fill=tk.BOTH,expand=True,side='top')
        self.btnSelect=tk.Button(self.f1, command=self.input_words, width=6, height=3)
        self.btnSelect.pack(padx=10, side='left')
        self.btnSelect['text'] = '选择文件'

        self.btnSelect=tk.Button(self.f1, command=self.reload_words, width=6, height=3)
        self.btnSelect.pack(padx=10, side='left')
        self.btnSelect['text'] = '重新开始'
        
        self.btnNext = tk.Button(self.f1, command=self.output_nextByte, width=6, height=3)
        self.btnNext.pack(padx=10, side='left')
        self.btnNext['text'] = '下一个'
        
        self.btnRWords = tk.Button(self.f1, command=self.output_rwords, width=6, height=3)
        self.btnRWords.pack(padx=10, side='left')
        self.btnRWords['text'] = '关联词语'
        
        self.btnMean = tk.Button(self.f1, command=self.output_mean, width=6, height=3)
        self.btnMean.pack(padx=10, side='left')
        self.btnMean['text'] = '查字典'

        self.btnMean = tk.Button(self.f1, command=self.record_maintain, width=6, height=3)
        self.btnMean.pack(padx=10, side='left')
        self.btnMean['text'] = '百度查询'

        btnQuit = tk.Button(self.f1, text='关闭窗口', command=self.root.quit, width=6, height=3)
        btnQuit.pack(padx=10, side='right')
        
        self.text1 = tk.Text(self.f2, width=600, height=400, font=Font(size=30) )
        self.scroll1 = tk.Scrollbar( self.f2, width=20 )
        
        self.scroll1.pack(side='right', fill=tk.Y)
        self.text1.pack(  fill=tk.BOTH,expand=True,side='left' )
        
        self.scroll1['command'] = self.text1.yview
        self.text1['yscrollcommand'] = self.scroll1.set
#        self.text1.config(state='disabled')
       
    def output_mean(self):
        mean = get_mean(self.theByte)
        self.text1.insert(tk.END,mean)
        self.text1.insert(tk.END, '\n')
        self.record_cuozi()
    
    def record_maintain(self):
        #with open('maintain.py','r',encoding='utf-8') as f:
        #    exec(f.read())
        mean = baidudict(self.theByte)
        if len(mean)>0:
            input_word(self.theByte,mean)
            self.text1.insert(tk.END,mean)
        else:
            self.text1.insert(tk.END,'百度查询失败。\n')
        
    def input_words(self, filename=''):
        if len(filename)==0:
            fp1=askopenfilename(filetypes=(("Text Files", "*.txt"), ),initialdir=os.path.dirname(sys.argv[0]))
        else:
            fp1=filename
        self.curFilename=fp1
        self.num=0
        if len(fp1)>0:
            self.words = file_input_words( fp1 )
            self.bytes = get_unique_bytes( self.words )
            self.rand_bytes = rand_bytes( self.bytes )
        names1=fp1.split('/')
        self.root.title('识字抽查--'+names1[len(names1)-1])
        self.text1.delete('0.0',tk.END)
        self.text1.insert('0.0', '\n请点击“下一个”\n')
        try:
            os.unlink('错字.txt')
        except:
            return

    def record_cuozi(self):
        fp = os.open('错字.txt',os.O_CREAT|os.O_APPEND|os.O_WRONLY)
        os.write(fp, (self.theByte+'\n').encode())
        #print(sys.stdout.encoding)
        os.close(fp)
        

    def reload_words(self):
        #if len(self.curFilename)==0:
            #return
        #fp1=self.curFilename
        self.num=0

        #self.words = file_input_words( fp1 )
       # self.bytes = get_unique_bytes( self.words )
        self.rand_bytes = rand_bytes( self.bytes )
        #names1=fp1.split('/')
        #self.root.title('识字抽查--'+names1[len(names1)-1])
        self.text1.delete('0.0',tk.END)
        self.text1.insert('0.0', '\n请点击“下一个”\n')
        try:
            os.unlink('错字.txt')
        except:
            return

    def output_nextByte(self):
        #self.text1.config(state='normal')
        self.text1.delete('1.0', tk.END)
        try:
            self.theByte = next( self.rand_bytes )
            #print(self.theByte)
            self.num += 1
            self.text1.insert('0.0', str(self.num)+'. '+self.theByte+'\n')
        except:
            self.text1.insert('0.0', '\n结束了\n')
        #self.text1.config(state='disabled')

    def output_rwords(self):
        #self.text1.config(state='normal')
        self.theRWords = get_rwords(self.theByte,self.words)
        for w1 in self.theRWords:
            #print(w1)
            self.text1.insert(tk.END,'  '+w1)
        self.text1.insert(tk.END, '\n')
        #self.text1.config(state='disabled')

    def loop(self):
        self.root.resizable(False, False)   #禁止修改窗口大小
        self.packBtn()
        self.center()                       #窗口居中
        self.root.mainloop()

########################################################################

def change_dir():
    cwd = os.path.dirname(sys.argv[0])

    if len(cwd)>0:
        os.chdir(cwd)
        
if __name__ == '__main__':
    change_dir()
    w = Window()
    if len(sys.argv)>1:
        w.input_words( sys.argv[1] )
    w.loop()
